package com.cincc.cincc_pbx.ui;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.cincc.cincc_pbx.R;
import com.cincc.cincc_pbx.adapter.CallRecordAdapter;
import com.cincc.cincc_pbx.common.MyUtils;
import com.cincc.cincc_pbx.common.OkHttpUtils;
import com.cincc.cincc_pbx.constant.CallConstant;
import com.cincc.cincc_pbx.model.CallRecordModel;
import com.cincc.cincc_pbx.model.EventBusModel;
import com.gyf.immersionbar.ImmersionBar;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.XXPermissions;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

public class HomeFragment extends Fragment {
    private static final String TAG = "HomeFragment";

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        initView(view);
        return view;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handleCommonEvent(EventBusModel event) {
        Log.e(TAG, "handleCommonEvent: " + event.toString());
        if (event.getEventName().equals(CallConstant.REFRESH_RECORD_EVENT)) {
            requestData();
        }
    }


    List<CallRecordModel> list = new ArrayList<>();
    RecyclerView recyclerView;
    SwipeRefreshLayout swipeRefreshLayout;
    ProgressBar progressBar;
    CallRecordAdapter callRecordAdapter;

    private void initView(View view) {
        TextView titleText = view.findViewById(R.id.title_tv);
        int statusBarHeight = ImmersionBar.getStatusBarHeight(this);
        ConstraintLayout.LayoutParams lp = (ConstraintLayout.LayoutParams) titleText.getLayoutParams();
        lp.topMargin = statusBarHeight + 10;
        titleText.setLayoutParams(lp);

        recyclerView = view.findViewById(R.id.record_recycler);
        progressBar = view.findViewById(R.id.progress_circular);
        swipeRefreshLayout = view.findViewById(R.id.swipeRefreshLayout);
        callRecordAdapter = new CallRecordAdapter(getActivity(), list);
        recyclerView.setAdapter(callRecordAdapter);
        callRecordAdapter.setOnClickItem(item -> {
            applyPermission(item.getPhone());
        });
        swipeRefreshLayout.setOnRefreshListener(this::requestData);
    }

    private void applyPermission(String phone) {
        XXPermissions.with(requireActivity()).permission(CallConstant.AUDIO_PERMISSION_LIST)
                .request(new OnPermissionCallback() {

                    @Override
                    public void onGranted(@NonNull List<String> permissions, boolean allGranted) {
                        if (!allGranted) {
                            Toast.makeText(getActivity(), "请授予全部权限，否则无法使用通话功能", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        EventBus.getDefault().post(new EventBusModel(CallConstant.MAKE_CALL, phone));
                    }

                    @Override
                    public void onDenied(@NonNull List<String> permissions, boolean doNotAskAgain) {
                        if (doNotAskAgain) {
                            Toast.makeText(getActivity(), "被永久拒绝授权，请手动授予对应权限", Toast.LENGTH_SHORT).show();
                            // 如果是被永久拒绝就跳转到应用权限系统设置页面
                            XXPermissions.startPermissionActivity(requireActivity(), permissions);
                        } else {
                            System.out.println("授予权限失败");
                        }
                    }
                });
    }


    private void refreshUI(String data) {
        try {
            JSONObject jsonObject = new JSONObject(data);
            if (jsonObject.getString("rtnCode").equals("0000")) {
                JSONArray jsonArray = jsonObject.getJSONObject("data").getJSONArray("list");
                for (int i = 0; i < jsonArray.length(); i++) {
                    String callingPartyNumber = jsonArray.getJSONObject(i).getString("callingpartynumber");
                    String calledPartyNumber = jsonArray.getJSONObject(i).getString("calledpartynumber");
                    String startDateAndTime = jsonArray.getJSONObject(i).getString("begintime");
                    int duration = jsonArray.getJSONObject(i).getInt("duration");
                    String releaseCause = jsonArray.getJSONObject(i).getString("releasecause");
                    String acrType = jsonArray.getJSONObject(i).getString("acrtype");

                    String phone = acrType.equals("1") ? calledPartyNumber : callingPartyNumber;
                    CallRecordModel model = new CallRecordModel(phone, startDateAndTime, duration, releaseCause, acrType);
                    list.add(model);
                }
                progressBar.setVisibility(View.GONE);
                callRecordAdapter.notifyDataSetChanged();
            } else {
                String msg = jsonObject.getString("rtnMsg");
                Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
        } finally {
            swipeRefreshLayout.setRefreshing(false);
        }
    }

    private void requestData() {
        try {
            list.clear();
            callRecordAdapter.notifyDataSetChanged();
            progressBar.setVisibility(View.VISIBLE);
            JSONObject params = new JSONObject();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("servicekey", "");
            jsonObject.put("total", "");
            jsonObject.put("pageSize", 50);
            jsonObject.put("pageNum", 1);
            jsonObject.put("starttime", MyUtils.getCurrentMonthTimeStr());
            jsonObject.put("endtime", MyUtils.getCurrentTimeStr());
            jsonObject.put("groupnumber", CallConstant.loginModel.getVccId());
            jsonObject.put("membernumber", MyUtils.getSipAccount());
            params.put("params", jsonObject);
            Log.e(TAG, "getRecord:params is " + params);

            Map<String, String> header = new HashMap<>();
            header.put("Authorization", "Bearer " + CallConstant.loginModel.getAccessToken());
            OkHttpUtils.httpPost(CallConstant.REQUEST_GET_RECORD_URL, params.toString(), header, new OkHttpUtils.ICallBack() {
                @Override
                public void onSuccessful(Call call, String data) {
                    Log.e(TAG, "getRecord onSuccessful: " + data);
                    requireActivity().runOnUiThread(() -> {
                        refreshUI(data);
                    });
                }

                @Override
                public void onFailure(Call call, String errorMsg) {
                    Log.e(TAG, "getRecord onFailure: " + errorMsg);
                    requireActivity().runOnUiThread(() -> Toast.makeText(getActivity(), errorMsg, Toast.LENGTH_SHORT).show());
                }
            });
        } catch (Exception e) {
            Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
        } finally {
            swipeRefreshLayout.setRefreshing(false);
        }
    }
}
